package group9;

import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Claudio Herreros, Dylan James, Tyler Berg
 *
 */

@SuppressWarnings("serial")
public class CreateAccountServlet extends HttpServlet {
	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {

		String userName = req.getParameter("UserName");
		String fullName = req.getParameter("FullName");
		String password = req.getParameter("Password");

		if (User.isLegalPassword(password))
		{
			
			//md5 encryption
			String encryptedPassword;
			try{
				MessageDigest crypt = MessageDigest.getInstance("MD5");
				crypt.update(password.getBytes(), 0, password.length());
				encryptedPassword = new BigInteger(1, crypt.digest()).toString(16);
			}catch(NoSuchAlgorithmException ie){
				
				req.setAttribute("errorMessage", "Encryption Error");
				RequestDispatcher rd = req.getRequestDispatcher("NewAccount.jsp");
				try {
					rd.forward(req, resp);
				} catch (ServletException e) {
					e.printStackTrace();
				}
				return;
			}
			
			
			User newUser = new User(fullName, userName, encryptedPassword);

			PersistenceManager pm = PMF.get().getPersistenceManager();
			Query userQuery = pm.newQuery("select from " + User.class.getName() + " where userName == '" + userName + "'");

			List<User> results = (List<User>) userQuery.execute();

			if (results.isEmpty())
			{
				try {
					pm.makePersistent(newUser);
				} finally {
					pm.close();
				}

				req.getSession(true).setAttribute("User", newUser);

				resp.sendRedirect("/home.jsp");

				return;
			} else {
				req.setAttribute("errorMessage", "User Name already exists");
				RequestDispatcher rd = req.getRequestDispatcher("NewAccount.jsp");
				try {
					rd.forward(req, resp);
				} catch (ServletException e) {
					e.printStackTrace();
				}
				return;
			}
		}
		else
		{
			req.setAttribute("errorMessage", "Password is not valid. Passwords must be at least eight characters long and have at least one letter, one number, and one special character (-, +, _, %, @, *, or &).");
			RequestDispatcher rd = req.getRequestDispatcher("NewAccount.jsp");
			try {
				rd.forward(req, resp);
			} catch (ServletException e) {
				e.printStackTrace();
			}
			return;
		}


	}

}
